package pe.edu.unmsm.pacis.shca.ams.impl;

import jade.core.Profile;
import jade.util.leap.Properties;
import jade.wrapper.gateway.JadeGateway;

import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import pe.edu.unmsm.pacis.shca.ams.BaseAgentService;
import pe.edu.unmsm.pacis.shca.domain.exception.DomainException;
import pe.edu.unmsm.pacis.shca.domain.message.GlobalMessage;

@Service
public abstract class BaseAgentServiceImpl implements BaseAgentService {
	
	private static final Logger logger = Logger.getLogger(BaseAgentServiceImpl.class);
	
	@Value("${ams.PLATFORM_ID}")
	private String PLATFORM_ID;
	@Value("${ams.REMOTE_HOST}")
	private String REMOTE_HOST;
	@Value("${ams.REMOTE_PORT}")
	private String REMOTE_PORT;
	@Value("${ams.CONTAINER_NAME}")
	private String CONTAINER_NAME;
	@Value("${ams.LOCAL_HOST}")
	private String LOCAL_HOST;
	@Value("${ams.LOCAL_PORT}")
	private String LOCAL_PORT;
	@Value("${ams.SERVICES}")
	private String SERVICES;	
	
	private String AGENT_CLASS_NAME = "pe.edu.unmsm.pacis.shca.ams.GateWay";
	
	private String remoteAgent;
	
	public BaseAgentServiceImpl(){
		
	}

	public String getRemoteAgent() {
		return remoteAgent;
	}

	public void setRemoteAgent(String remoteAgent) {
		this.remoteAgent = remoteAgent;
	}
	
	protected Map<String,Object> executeCommand(Map<String,Object> sendMessage) throws DomainException{
		this.createAgent();
		GlobalMessage globalMessage = new GlobalMessage();
		globalMessage.setSend(sendMessage);
		globalMessage.setRemoteAgent(this.getRemoteAgent());
		try {
			JadeGateway.execute(globalMessage);
			JadeGateway.shutdown();
		} catch (Exception e) {
			logger.error("Exception", e);
			throw new DomainException("No execution message in JADE.", "ams.exception.noExecute", e);
		}
		return globalMessage.getReply();
	}
	
	private void createAgent(){
		Properties p = new Properties();
		p.setProperty(Profile.PLATFORM_ID, this.PLATFORM_ID);
		p.setProperty(Profile.MAIN_PORT, this.REMOTE_PORT);
		p.setProperty(Profile.MAIN_HOST, this.REMOTE_HOST);
		p.setProperty(Profile.CONTAINER_NAME, this.CONTAINER_NAME);
		p.setProperty(Profile.LOCAL_HOST, this.LOCAL_HOST);
		p.setProperty(Profile.LOCAL_PORT, this.LOCAL_PORT);
		p.setProperty(Profile.SERVICES, this.SERVICES);
		JadeGateway.init(this.AGENT_CLASS_NAME, p);
	}
}
